import {BaseProps} from "../../App";
import React from "react";
import {Button, CardActions, TextField} from "@material-ui/core";
import "./Login.css";
import {UserApi} from "../../framework/api/UserApi";
import {Token} from "../../framework/Token";

interface LoginState {
    username: string;
    password: string;

}

export class Login extends React.Component<BaseProps, LoginState> {

    constructor(props: BaseProps) {
        super(props);
        this.inputChange = this.inputChange.bind(this);
        this.login = this.login.bind(this);
        this.state = {username: '', password: ''};
    }

    inputChange(e: any) {
        let state: any = {...this.state};
        state[e.target.name] = e.target.value;
        this.setState(state);
    }

    login() {
        UserApi.login(this.state.username, this.state.password).then(res => {
            Token.login(this.state.username, this.state.password, res);
            window.location.reload();
        });
    }


    render(): React.ReactElement | string | number | {} | React.ReactNodeArray | React.ReactPortal | boolean | null | undefined {
        return <div className={'login-content'}>
            <div className={'login-card'}>
                <div className={'login-input'}>
                    <TextField size='small' label="用户名" name='username' variant="outlined" color="primary"
                               onChange={this.inputChange}/>
                </div>
                <div>
                    <TextField type={'password'} size='small' label="密码" name='password' variant="outlined"
                               color="primary"
                               onChange={this.inputChange}/>
                </div>
                <CardActions>
                    <Button size="small" variant="contained" color="primary" onClick={this.login}>登录</Button>
                </CardActions>
            </div>
        </div>
    }
}
